<template>
  <div>
    <a-card class="card" :bordered="false">
      <role-base-form ref="baseForm" :role-info="roleInfo"></role-base-form>
    </a-card>

    <a-card style="margin-bottom: 80px" title="权限配置" :bordered="false">
      <role-permission-tree
        ref="permissionTree"
        :default-checked-keys="defaultCheckedPermissions"></role-permission-tree>
    </a-card>

    <!-- fixed footer toolbar -->
    <footer-tool-bar
      :style="{ width: isSideMenu() && isDesktop() ? `calc(100% - ${sidebarOpened ? 256 : 80}px)` : '100%'}">
      <span class="popover-wrapper">
        <a-popover
          title="表单校验信息"
          overlayClassName="antd-pro-pages-forms-style-errorPopover"
          trigger="click"
          :getPopupContainer="trigger => trigger.parentNode">
          <template slot="content">
            <li
              v-for="item in errors"
              :key="item.key"
              @click="scrollToField(item.key)"
              class="antd-pro-pages-forms-style-errorListItem">
              <a-icon type="cross-circle-o" class="antd-pro-pages-forms-style-errorIcon"/>
              <div class="">{{ item.message }}</div>
              <div class="antd-pro-pages-forms-style-errorField">{{ item.fieldLabel }}</div>
            </li>
          </template>
          <span class="antd-pro-pages-forms-style-errorIcon" v-if="errors.length > 0">
            <a-icon type="exclamation-circle"/>{{ errors.length }}
          </span>
        </a-popover>
      </span>
      <a-button type="primary" @click="validate" :loading="loading">提交</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
  import FooterToolBar from '@/components/FooterToolbar'
  import { mixin, mixinDevice } from '@/utils/mixin'
  import RoleBaseForm from '@/views/system/role_management/module/RoleBaseForm'
  import RolePermissionTree from '@/views/system/role_management/module/RolePermissionTree'
  import { saveRole, getRoleInfo } from '@/api/system'

  const fieldLabels = {
    roleName: '角色名'
  }

  export default {
    name: 'AdvancedForm',
    mixins: [mixin, mixinDevice],
    components: {
      RolePermissionTree,
      RoleBaseForm,
      FooterToolBar
    },
    data () {
      return {
        loading: false,
        memberLoading: false,

        errors: [],

        roleInfo: {},
        defaultCheckedPermissions: []
      }
    },
    mounted () {
      if (this.$route.params && this.$route.params.hasOwnProperty('roleId')) {
        getRoleInfo({ id: this.$route.params.roleId })
          .then(res => {
            this.roleInfo = res
            this.defaultCheckedPermissions = res.permissions
          })
      }
    },
    methods: {
      // 最终全页面提交
      validate () {
        const { $refs: { baseForm, permissionTree } } = this
        const baseFormPromise = new Promise((resolve, reject) => {
          baseForm.form.validateFields((err, values) => {
            if (err) {
              reject(err)
              return
            }
            resolve(values)
          })
        })
        const permissionTreePromise = new Promise((resolve, reject) => {
          permissionTree.submit((err, values) => {
            if (err) {
              reject(err)
              return
            }
            resolve(values)
          })
        })

        this.errors = []
        Promise.all([baseFormPromise, permissionTreePromise]).then(values => {
          saveRole(
            Object.assign(
              values[0],
              { 'permissions': values[1]['permissions'] },
              (() => this.$route.params.hasOwnProperty('roleId') ? { id: this.$route.params.roleId } : {})())) // 编辑的情况下需要传 ID
            .then(res => {
              this.$router.push('/system/role_management/list')
            })
            .catch(e => console.log(e))
        }).catch(() => {
          const errors = Object.assign({}, baseForm.form.getFieldsError())
          const tmp = { ...errors }
          this.errorList(tmp)
        })
      },
      errorList (errors) {
        if (!errors || errors.length === 0) {
          return
        }
        this.errors = Object.keys(errors)
          .filter(key => errors[key])
          .map(key => ({
            key: key,
            message: errors[key][0],
            fieldLabel: fieldLabels[key]
          }))
      },
      scrollToField (fieldKey) {
        const labelNode = document.querySelector(`label[for="${fieldKey}"]`)
        if (labelNode) {
          labelNode.scrollIntoView(true)
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .card {
    margin-bottom: 24px;
  }

  .popover-wrapper {
    /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
      min-width: 256px;
      max-height: 290px;
      padding: 0;
      overflow: auto;
    }
  }

  .antd-pro-pages-forms-style-errorIcon {
    user-select: none;
    margin-right: 24px;
    color: #f5222d;
    cursor: pointer;

    i {
      margin-right: 4px;
    }
  }

  .antd-pro-pages-forms-style-errorListItem {
    padding: 8px 16px;
    list-style: none;
    border-bottom: 1px solid #e8e8e8;
    cursor: pointer;
    transition: all .3s;

    &:hover {
      background: #e6f7ff;
    }

    .antd-pro-pages-forms-style-errorIcon {
      float: left;
      margin-top: 4px;
      margin-right: 12px;
      padding-bottom: 22px;
      color: #f5222d;
    }

    .antd-pro-pages-forms-style-errorField {
      margin-top: 2px;
      color: rgba(0, 0, 0, .45);
      font-size: 12px;
    }
  }
</style>
